package xing.appwidget.storage

import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import xing.appwidget.BuildConfig
import xing.appwidget.bean.ApplicationItem
import xing.appwidget.bean.PackageFilterParam
import xing.appwidget.utils.Utils

class AppInfoStorageHelper {

    companion object {
        private val TAG = AppInfoStorageHelper::class.java.simpleName

        private val packageInfoList: MutableList<PackageInfo> = ArrayList()

        fun getAppInfoWithFilter(pm: PackageManager, filter: PackageFilterParam): Single<List<ApplicationItem>> {
            return Single.just(filter)
                    .map { f -> getAppInfoList(pm, f) }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
        }

        fun getAppInfoList(pm: PackageManager, filter: PackageFilterParam): List<ApplicationItem> {
            if (packageInfoList.isEmpty()) {
                packageInfoList.addAll(pm.getInstalledPackages(PackageManager.GET_ACTIVITIES))
            }
            val resultList = ArrayList<ApplicationItem>()
            for (packageInfo in packageInfoList) {
                if (BuildConfig.APPLICATION_ID == packageInfo.applicationInfo.packageName) {
                    continue
                }
                if (filter.isValid(packageInfo)) {
                    resultList.add(Utils.toApplicationItem(pm, packageInfo))
                }
            }
            return resultList
        }
    }
}